package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.QueryObject.StrategyCatalogQuery;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.respository.DestinationRespository;
import cn.wolfcode.luowowo.respository.StrategyCatalogRespository;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.DBHelper;
import cn.wolfcode.luowowo.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
//@Transactional  暂时不管事务
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRespository strategyCatalogrRespository;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private DestinationRespository destinationRespository;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public StrategyCatalog get(String id) {
        Optional<StrategyCatalog> optional = strategyCatalogrRespository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public List<StrategyCatalog> list() {
        return strategyCatalogrRespository.findAll();
    }

    @Override
    //Page对象里面包括 : 总页数 每页显示条数
    //使用mongoTemplate 只能返回Page 需要把list封装成 page对象再返回
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {
        //1.查询总条数 total
        Query query = new Query();
        PageRequest page = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "sequence");
        return DBHelper.query(mongoTemplate, StrategyCatalog.class, query, page);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        if (!StringUtils.hasLength(strategyCatalog.getId())) {
            Optional<Destination> optional = destinationRespository.findById(strategyCatalog.getDestId());
            if (optional.isPresent()) {
                Destination destination = optional.get();
                strategyCatalog.setDestName(destination.getName());
            }
            //添加
            strategyCatalog.setId(null);
            strategyCatalogrRespository.save(strategyCatalog);
        } else {
            //更新
            //方案一: 1.查询 2.替代 3.save
            //方案二:

            //条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(strategyCatalog.getId()));
            //更新的列
            Optional<Destination> optional = destinationRespository.findById(strategyCatalog.getDestId());
            if (optional.isPresent()) {
                Destination destination = optional.get();
                strategyCatalog.setDestName(destination.getName());
            }
            Update update = new Update();
            update.set("destId", strategyCatalog.getDestId());
            update.set("destName", strategyCatalog.getDestName());
            update.set("state", strategyCatalog.getState());
            update.set("name", strategyCatalog.getName());
            update.set("sequence", strategyCatalog.getSequence());
            mongoTemplate.updateMulti(query, update, StrategyCatalog.class);
        }
    }

    @Override
    public void delete(String id) {
        strategyCatalogrRespository.deleteById(id);
    }

    @Override
    public List<CatalogVO> groupList() {
        List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        addToSet("name").as("names").
                        addToSet("id").as("ids")
        );
        AggregationResults<Map> result = mongoTemplate.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        System.out.println(datas);
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0; i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setMapList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    @Override
    public List<StrategyCatalog> getCatalogByDsetId(String id) {
        List<StrategyCatalog> list = strategyCatalogrRespository.findByDestId(id);
        //根据攻略分类id  获取对应的攻略文章
        for (StrategyCatalog catalog : list) {
            List<Strategy> strategies = strategyService.getStrategyByCatalogId(catalog.getId());
            catalog.setStrategies(strategies);
        }
        return list;
    }


}
